4/7/2017

Why be interactive?

… It's super cool!

Examples on the web

Main tools in R

Make your scatter plots, line plots, bar plots, etc interactive

  • Plotly

  • Highcharts

  • crosstalk

Make D3.js plots in R (no javascript required!)

  • rCharts (D3.js)

  • d3scatter

  • networkD3

Making ggplot2 interactive

ggplot2

library(ggplot2)
g <- ggplot(txhousing, aes(x = date, y = sales, group = city)) +
  geom_line(alpha = 0.4)
g

ggplot2 + plotly

library(plotly)
g <- ggplot(txhousing, aes(x = date, y = sales, group = city)) +
  geom_line(alpha = 0.4) 
ggplotly(g, tooltip = c("city"))

plotly

g <- txhousing %>% 
  # group by city
  group_by(city) %>%
  # initiate a plotly object with date on x and median on y
  plot_ly(x = ~date, y = ~median) %>%
  # add a line plot for all texan cities
  add_lines(name = "Texan Cities", hoverinfo = "none", 
            type = "scatter", mode = "lines", 
            line = list(color = 'rgba(192,192,192,0.4)')) %>%
  # plot separate lines for Dallas and Houston
  add_lines(name = "Houston", 
            data = filter(txhousing, 
                          city %in% c("Dallas", "Houston")),
            hoverinfo = "city",
            line = list(color = c("red", "blue")),
            color = ~city)
g

plotly

plotly: adding a slider

g %>% rangeslider

Linking with Crosstalk

Linking with Crosstalk

library(crosstalk)
library(htmltools)
# define a SharedData object, grouping by year
sd <- SharedData$new(txhousing, ~city)
# plot median house prices by month, with one line per year
p <- sd %>% ggplot(aes(date, median)) +
  geom_line() 
# turn plot into a plotly object
gg <- ggplotly(p, hoverinfo = "city")
# highlight options
highlight(gg, on = "plotly_click", dynamic = TRUE)
highlight(gg, on = "plotly_click", dynamic = TRUE, persistent = TRUE)

Linking with Crosstalk

Easy D3.js in R

Force networks

library(networkD3)
data(MisLinks, MisNodes)
head(MisLinks, 4)
##   source target value
## 1      1      0     1
## 2      2      0     8
## 3      3      0    10
## 4      3      2     6
head(MisNodes, 4)
##              name group size
## 1          Myriel     1   15
## 2        Napoleon     1   20
## 3 Mlle.Baptistine     1   23
## 4    Mme.Magloire     1   30
forceNetwork(Links = MisLinks, Nodes = MisNodes, Source = "source",
             Target = "target", Value = "value", NodeID = "name",
             Group = "group", opacity = 0.9, Nodesize = 3, 
             linkDistance = 100, fontSize = 20)

Force networks